package link;

public class leetCode61_rotateRight {
    public static void main(String[] args) {

    }
    public ListNode rotateRight(ListNode head, int k) {
       if(head == null) return null;
       int n = 1;
       ListNode tmp = head;
       while (tmp.next !=null){
           n++;
           tmp = tmp.next;
       }
       k = k%n;
       if(k == 0){
           return head;
       }
       int p = n - k - 1; // 5 -2 - 1 = 2
       ListNode newTail = head;
       while (p > 0){
           newTail = newTail.next;
           p--;
       }
       ListNode newHead = newTail.next;
        newTail.next = null;

        tmp.next = head;


       return newHead;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
